﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ELTE.SEM.Common;
using System.Data.Entity;
using ELTE.SEM.Data.ViewModels;

namespace ELTE.SEM.Data.Repository
{
    public class UsersRepository : Repository<User>, IUsersRepository
    {
        public UsersRepository(DbContext context)
            :base(context)
        {
 
        }

        public bool RegisterUser(User user)
        {
            try
            {
                Insert(user);
                if (user.UsersInRoles.Count == 0)
                {
                    user.UsersInRoles.Add(new UsersInRole { Created= DateTime.Now, UserRoleId = 5 });
                    //ha nincs szint definiálva, az alapértelmezett a "betekintői"
                }
                Save();
                return true;
            }
            catch (Exception ex)
            {
                //TODO: log error;
                return false;
            }
            
        }

        public User Login(string userName, string password)
        {
            try
            {
                var allLogins = GetAll().ToList();
                return allLogins.SingleOrDefault(u =>
                    u.Name.Equals(userName)
                    && u.Password.Equals(Encrypter.Encrypt(password)));
            }
            catch (Exception ex)
            {
                //TODO: log error
            }
            return null;
        }

        public bool HasUser(string UserName)
        {
            return GetAll().Any(user => user.Name == UserName);
        }


        public List<UserViewModel> GetUsersAndRoles()
        {
            return GetAll().Select(user => new UserViewModel { }).ToList();
        }

        public int GetUserId(string userName)
        {
            User user = DbSet.SingleOrDefault(u => u.Name == userName);
            if (user != null)
            {
                return user.Id;
            }
            else
            {
                return 0;
            }
        }


        public List<UserRole> GetAvailableUserRoles()
        {
            return _context.Set<UserRole>().OrderBy(r => r.RoleDisplayName).ToList();
        }


        public UserRole GetRoleById(int id)
        {
            return _context.Set<UserRole>().SingleOrDefault(role => role.Id == id);
        }
    }
}
